package com.liwei.easyweibo.api;

import java.io.IOException;

import android.app.ProgressDialog;
import android.content.Context;
import android.text.TextUtils;

import com.liwei.easyweibo.activity.WriteWeiboActivity;
import com.liwei.easyweibo.util.Constant;
import com.liwei.easyweibo.util.Util;
import com.sina.net.AccessToken;
import com.sina.net.AsyncWeiboRunner;
import com.sina.net.AsyncWeiboRunner.RequestListener;
import com.sina.net.Weibo;
import com.sina.net.WeiboException;
import com.sina.net.WeiboParameters;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXTextObject;
import com.tencent.weibo.api.TAPI;
import com.tencent.weibo.constants.OAuthConstants;
import com.tencent.weibo.oauthv2.OAuthV2;
import com.liwei.easyweibo.R;


public class WeiboShare {
	private final static String TAG = "WeiboShare";
	private String mContent;
	
	private ProgressDialog mShareProgress;
	private String mPicFilePath ="";
	
	private IWXAPI mApi;
	
	private Context mContext;
	
	public WeiboShare(Context context,String content){
		mContext	= context;
		mContent 	= content;
		
	}
	
	public WeiboShare(Context context){
		mContext 	= context;
		mApi = WXAPIFactory.createWXAPI(mContext, Constant.WECHAT_APPID);
	}
	
	/**
	 * 新浪微博发送一条没有图片的微博
	 * @param weibo Weibo 的一个实例，包含token信息
	 * @param source private static String APP_KEY = "710259867";
	 * @param status 	为发送微博的文字内容
	 * @param lon,lat 为用户所在位置的纬度和经度
	 * 
	 * @return 暂时没有用到
	 * */
	private  String update(Weibo weibo,String source, String status, String lon, String lat){
		WeiboParameters bundle = new WeiboParameters();
		bundle.add("source", source);
		bundle.add("status", status);
		if(!TextUtils.isEmpty(lon)){
			bundle.add("lon", lon);
		}
		if(!TextUtils.isEmpty(lat)){
			bundle.add("lat", lat);
		}
		String result = "";
		String url = Constant.SERVER +"statuses/update.json";
		AsyncWeiboRunner weiboRunner = new AsyncWeiboRunner(weibo);
		weiboRunner.request(mContext,url, bundle, Constant.HTTPMETHOD_POST, requestListener);
		return result;
	}
	
	/**
	 * 新浪微博发送一条没有图片的微博
	 * @param weibo Weibo 的一个实例，包含token信息
	 * @param source private static String APP_KEY = "710259867";
	 * @param picpath 为图片的路径
	 * @param status 	为发送微博的文字内容
	 * @param lon,lat 为用户所在位置的纬度和经度
	 * 
	 * @return 暂时没有用到
	 * */
	
	private  String update(Weibo weibo,String source, String picPath, String status, String lon, String lat){
		WeiboParameters bundle = new WeiboParameters();
		bundle.add("source", source);
		bundle.add("pic", picPath);
		bundle.add("status", status);
		if(!TextUtils.isEmpty(lon)){
			bundle.add("lon", lon);
		}
		if(!TextUtils.isEmpty(lat)){
			bundle.add("lat", lat);
		}
		String result = "";
		String url = Constant.SERVER +"statuses/update.json";
		AsyncWeiboRunner weiboRunner = new AsyncWeiboRunner(weibo);
		weiboRunner.request(mContext,url, bundle, Constant.HTTPMETHOD_POST, requestListener);
		return result;
	}
	
	/**
	 * 用于handle 发送微博之后返回的状态信息
	 * 发送成功、错误、异常。
	 * */
	RequestListener requestListener = new RequestListener() {
		WriteWeiboActivity activity = (WriteWeiboActivity)mContext;
		
		@Override
		public void onComplete(String arg0) {
			dismissDialog();
			// TODO Auto-generated method stub
			
			activity.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					handleSharing(R.string.send_sucess);
					Util.d(TAG, "分享成功");
				}
			});
		}
		
		@Override
		public void onIOException(IOException arg0) {
			dismissDialog();
			// TODO Auto-generated method stub
			activity.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					handleSharing(R.string.send_failed);
					Util.d(TAG, "分享失败");
				}
			});
		}
		
		@Override
		public void onError(final WeiboException e) {
			dismissDialog();
			// TODO Auto-generated method stub
			activity.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					Util.d(TAG, e.getMessage() + "错误码为 " +e.getStatusCode());
				}
			});
		}
	};
	
	/**
	 * 处理结果以字符串的形式展现出来。
	 * @param showContentId 是字符串的id
	 * */
	private void handleSharing(int showContentId){
		String info=mContext.getResources().getString(showContentId);
		switch(showContentId){
		case com.liwei.easyweibo.R.string.oauth_failed:{
			Util.showToast(mContext, info);
			break;
		}
		case R.string.net_not_available:{
			Util.showToast(mContext, info);
			break;
		}
		case R.string.access_token_expired:{
//			mContext.setShareBtnState();
			Util.showToast(mContext, info);
			return;
		}
		case R.string.send_failed_repeat_or_not:{
			Util.showToast(mContext, info);
			break;
		}
		case R.string.send_failed:{
			Util.showToast(mContext, info);
			break;
		}
		case R.string.send_sucess:{
			Util.showToast(mContext, info);
			break;
		}
		case R.string.time_out:{
			Util.showToast(mContext, info);
			break;
		}
		}
	}
	
	/**
	 * 分享微博，给Activity调用的接口
	 * @param type 标识是腾讯还是新浪微博，
	 * */
	public void shareToPlatform(int type){
		if(Constant.TYPE_WEIBO_SINA == type){
			shareToSinaWeibo();
		}else if(Constant.TYPE_WEIBO_TENCENT == type){
			shareToTencentWeibo();
		}else{
			//其他的平台
//			shareToWechat();
		}
	}
	
	/**
	 * 分享到新浪微博
	 * */
	private void shareToSinaWeibo(){
		if(mShareProgress==null || !mShareProgress.isShowing()){
			showProgress();
		}
		
		new Thread(){
			public void run() {
				toSinaWeibo();
			};
		}.start();
	}
	
	/**
	 * 分享到腾讯微博
	 * */
	private  void shareToTencentWeibo(){
		if(mShareProgress==null || !mShareProgress.isShowing()){
			showProgress();
		}
		
		new Thread(){
			public void run() {
				toTencentWeibo();
			};
		}.start();
	}
	
	/**
	 * 分享到微信
	 * */
	private void shareToWechat(){
		if(mShareProgress==null || !mShareProgress.isShowing()){
			showProgress();
		}
		
		new Thread(){
			public void run() {
				toWechat();
			};
		}.start();
	}
	
	public String getmContent() {
		return mContent;
	}

	public void setmContent(String mContent) {
		this.mContent = mContent;
	}
	
	
	
	public String getmPcFilePath() {
		return mPicFilePath;
	}

	public void setmPcFilePath(String mPcFilePath) {
		this.mPicFilePath = mPcFilePath;
	}

	public void showProgress(){
		if(mShareProgress == null){
			mShareProgress = new ProgressDialog(mContext);
			mShareProgress.setCancelable(true);
			mShareProgress.setTitle(R.string.sharing_please_wait);
		}
		mShareProgress.show();
	}
	
	public void dismissDialog(){
		if(mShareProgress != null){
			mShareProgress.dismiss();
		}
	}
	
	/**
	 * 分享到新浪微博的选择
	 * 根据mPicFilePath是否为null，即是否发送有图片的微博
	 * */
	private void toSinaWeibo(){
		String sinaAccessToken = Util.readSFromPreference(mContext, Constant.SHAREDPRE_SINA_TOKEN);
		AccessToken accessToken = new AccessToken(sinaAccessToken, Constant.SINA_APP_SECRET);
		Weibo weibo = Weibo.getInstance();
		weibo.setAccessToken(accessToken);
		try{
			if(!TextUtils.isEmpty(mContent) && !"".equals(mPicFilePath)){
				update(weibo,Weibo.getAppKey(),mPicFilePath, mContent, "", "");
			}else if(!TextUtils.isEmpty(mContent) && "".equals(mPicFilePath)){
				update(weibo,Weibo.getAppKey(), mContent, "", "");
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 分享到腾讯微博的选择
	 * 有图片和无图片，根据mPicFilePath是否为null来进行判断
	 * */
	private void toTencentWeibo(){
		if(!TextUtils.isEmpty(mContent) && !"".equals(mPicFilePath)){
			//有图的情况稍后再加
			update(mContent, mPicFilePath);
		}else if(!TextUtils.isEmpty(mContent) && "".equals(mPicFilePath)){
			update(mContent);
		}
	}
	
	/**
	 * 腾讯微博，发送一条没有图片的微博
	 * @param content 发送微博的内容
	 * 
	 * */
	private void update(String content){
		TAPI tapi = new TAPI(OAuthConstants.OAUTH_VERSION_2_A);
		OAuthV2 oAuth = Util.readTencentFromPreference(mContext);
		String clientip = oAuth.getClientIP();
		try {
			Util.d(TAG, "clientip = "+clientip);
			String result = tapi.add(oAuth, "json", content, clientip);
			if(result != null){
				dismissDialog();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 腾讯微博，发送一条含有图片的微博
	 * @param content 发送微博的内容
	 * @param picPath 为图片的路径
	 * 
	 * */
	public void update(String content, String picPath){
		TAPI tapi = new TAPI(OAuthConstants.OAUTH_VERSION_2_A);
		OAuthV2 oAuth = Util.readTencentFromPreference(mContext);
		String clientip = oAuth.getClientIP();
		try {
			Util.d(TAG, "clientip = "+clientip);
//			String result = tapi.add(oAuth, "json", content, clientip);
			String result = tapi.addPic(oAuth, "json", content, clientip, picPath);
			if(result != null){
				dismissDialog();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 分享到微信，选择是文字还是图片
	 * */
	private void toWechat(){
		
		if(!TextUtils.isEmpty(mContent) && !"".equals(mPicFilePath)){
			//有图的情况稍后再加
			sendImageMsg(mPicFilePath);
		}else if(!TextUtils.isEmpty(mContent) && "".equals(mPicFilePath)){
			sendMsg(mContent);
		}
	}
	
	private void sendMsg(String mContent){
		//初始化一个WXTestObject,用于描述一个文本对象
		WXTextObject textObj = new WXTextObject();
		textObj.text = mContent;
		
		//用WXTextObject对象初始化一个WXMedia对象  微信媒体消息内容
		WXMediaMessage msg = new WXMediaMessage();
		msg.mediaObject = textObj;
		// 发送文本类型的消息时，title字段不起作用
		// msg.title = "Will be ignored";
		msg.description 	= mContent;
		
		//构造一个请求到微信  SendMessageToWX请求类，继承自BaseReq
		SendMessageToWX.Req req = new SendMessageToWX.Req();
		req.transaction = buildTransaction("text");
		req.message = msg;
		req.scene		=SendMessageToWX.Req.WXSceneTimeline;
		
		//调用api接口发送数据到微信
		boolean isSuccess = mApi.sendReq(req);
		if(isSuccess){
			dismissDialog();
		}
	} 
	
	private void sendImageMsg(String picPath){
		//初始化一个WXTestObject,用于描述一个文本对象
		WXTextObject textObj = new WXTextObject();
		textObj.text = mContent;
		
		//用WXTextObject对象初始化一个WXMedia对象  微信媒体消息内容
		WXMediaMessage msg = new WXMediaMessage();
		msg.mediaObject = textObj;
		// 发送文本类型的消息时，title字段不起作用
		// msg.title = "Will be ignored";
		msg.description 	= mContent;
		
		//构造一个请求到微信  SendMessageToWX请求类，继承自BaseReq
		SendMessageToWX.Req req = new SendMessageToWX.Req();
		req.transaction = buildTransaction("text");
		req.message = msg;
		req.scene		=SendMessageToWX.Req.WXSceneTimeline;
		
		//调用api接口发送数据到微信
		boolean isSuccess = mApi.sendReq(req);
		if(isSuccess){
			dismissDialog();
		}
	} 
	private String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
	}
	
	
	/**
	 * 获取腾讯微博内容
	 * @param pageflag 分页标识（0：第一页，1：向下翻页，2：向上翻页
	 * @param pagetime 本页起始时间（第一页：填0，向上翻页：填上一次请求返回的第一条记录时间，向下翻页：填上一次请求返回的最后一条记录时间）
	 * @param reqnum	 每次请求记录的条数。取值为1-70条
	 * 
	 * @return 返回获取微博的内容，可以是xml或者json的格式，如有异常返回null
	 * */
	public String  getTencentWeiboContent(int pageflag, long pagetime,int reqnum){
		TAPI tapi = new TAPI(OAuthConstants.OAUTH_VERSION_2_A);
		OAuthV2 oAuth = Util.readTencentFromPreference(mContext);
		
		try {
			String result = tapi.getWeiboList(oAuth, "json", pageflag, pagetime, reqnum, 0, 0);
			Util.d(TAG, "result == " +result);
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}
}
